package com.nowcoder.community.aspect;

import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Aspect
public class ServiceLogAspect {

    //记日志，实例化Log
    private static final Logger logger = LoggerFactory.getLogger(ServiceLogAspect.class);


    /**
     *   1.定义切点
     *      1.1方法
     *      1.2切点表达式： 返回值类型 包名.文件名.方法名(参数)
     *
     */
    @Pointcut("execution(* com.nowcoder.community.service.*.*(..))")
    public void pointcut(){}

    /**
     *  2.定义通知
     */
    @Before("pointcut()")
    public void before(JoinPoint joinPoint){
        //用户[ip],在[什么时间],访问了[什么方法:com.nowcoder.community.service.xxx()].
        //获取ip
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String ip = request.getRemoteHost();
        //获取时间
        String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        //获取执行的方法名(参数引入JointPoint)
        String target = joinPoint.getSignature().getDeclaringType()+"."+ joinPoint.getSignature().getName();
        //打印日志
        logger.info(String.format("用户[%s]，在[%s],访问了[%s].",ip,now,target));
    }
}
